<template>
  <div style="width: 148px">
    <el-upload :class="{ disabled: disabled }" action="#" :file-list="fileList" :on-remove="onRemove" :on-change="onChange" :on-preview="onPreview" :before-upload="beforeUpload" :http-request="httpRequest" list-type="picture-card">
      <i class="el-icon-plus" />
    </el-upload>
    <el-dialog title="预览图片" :visible.sync="dialogShow">
      <img style="width: 100%" :src="imgUrl" alt="">
    </el-dialog>
    <el-progress v-if="percentageShow" :percentage="percentageNum" />
  </div>
</template>
<script>
export default {
  name: 'ImageUpload',
  data() {
    return {
      fileList: [],
      dialogShow: false,
      imgUrl: '',
      currentUid: '',
      percentageNum: 0,
      percentageShow: false
    }
  },
  computed: {
    disabled() {
      return this.fileList.length === 1
    }
  },
  methods: {
    // 图片移除的时候，更新fileList
    onRemove(file, fileList) {
      this.fileList = fileList
    },
    // 文件状态改变时的钩子，添加文件、上传成功或上传失败时都会被调用
    onChange(file, fileList) {
      this.fileList = fileList
    },
    // 图片预览的时候
    onPreview(file) {
      this.dialogShow = true
      this.imgUrl = file.url
    },
    // 上传成功之前的钩子
    beforeUpload(file) {
      // 1.格式校验
      const typeArr = ['image/png', 'image/gif', 'image/jpg', 'image/jpeg']
      if (!typeArr.includes(file.type)) {
        this.$message.warning('格式不正确')
        return false
      }
      // 2.体积校验
      if (file.size > 1024 * 1024 * 20) {
        this.$message.warning('体积不允许超过2M')
        return false
      }
      // 返回true，让其可以上传
      this.currentUid = file.uid
      this.percentageShow = true
      return true
    },
    // 覆盖上传行为的钩子
    httpRequest(data) {
      // console.log(data.file); // 要上传的文件信息
      // 传统的做法：封装上传的请求方法； new FormData 实例；  传入文件数据 ； 调用请求方法
      /*
        let fd = new FormData()
        fd.append('文件字段名',data.file)
        let res = await 上传的请求方法(fd)
        res里面有后端返回的存储地址，将地址信息放在fileList里面去
        // 注意：记录uploaded为true，记录进度条关闭
      */
    }
  }
}
</script>
<style scoped lang="scss">
.disabled {
  ::v-deep .el-upload--picture-card {
    display: none;
  }
}
</style>
